/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.mq.service.schedulerservice.connectionobject;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.fbagent.service.SerchFBService;
import com.ndp.fb.model.fbagent.param.serach.SearchParam;
import com.ndp.fb.model.fbagent.param.serach.SearchType;
import com.ndp.fb.model.fbagent.result.common.FBAdDestination;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.mq.api.service.schedulerservice.AppCpaAccessService;
import com.ndp.fb.rdb.api.*;
import com.ndp.fb.rdb.model.AdPublishAppAccountCPA;
import com.ndp.fb.rdb.model.ConnectionObject;
import com.ndp.fb.rdb.model.EntrustAccount;
import com.ndp.fb.rdb.model.ProductConfiguration;
import com.ndp.fb.util.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Title: AppCpaAccess.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 下午4:06:58
 * @author giser.yang
 */
@Service
public class AppCpaAccessServiceImpl implements AppCpaAccessService {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * @discription
	 * @author giser.yang 创建时间 2015年5月29日 下午4:09:09
	 */
	@Reference
	SerchFBService serchFBService;
	@Reference
	BusinessManagerRdbService businessManagerRdbService;
	@Reference
	EntrustAccountRdbService entrustAccountRdbService;
	@Reference
	EntrustAccountConnectionObjectsRdbService entrustAccountConnectionObjectsRdbService;
	@Reference
	ConnectionObjectRdbService connectionObjectRdbService;
	@Reference  
	AdPublishAppAccountCPARdbService adPublishAppAccountCPARdbService;
	@Reference
	AdAccountsSchedulerService adaccountsSchedulerService;
	@Reference  
	ProductConfigurationRdbService productConfigurationRdbService;
	public  AppCpaAccessServiceImpl (){
		
	}
	@Override
	public Long getAppCpaAccessInfo(Boolean isAll) {
		ThreadPool.execute(() -> synBusinessManager());
		return 0L;
	}

	private void synBusinessManager() {
		try {
			List<EntrustAccount> entrustAccounts = entrustAccountRdbService.findAdAccountListByRoles("ADMIN","GENERAL_USER","REPORTS_ONLY");
			FBAdDestination fbAdDestination = null;
			if (CollectionUtils.isEmpty(entrustAccounts)) {
				logger.warn("系统没有广告账号!");
				return;
			}
			
			for (EntrustAccount entrustAccount : entrustAccounts) {
				Long fbAccountId = entrustAccount.getFbAccountId();
				logger.info("开始获取账号{}下应用的cpa权限信息",fbAccountId);
				String token = adaccountsSchedulerService.getAdaccountsToken(fbAccountId);
				List<ConnectionObject> connectionObjects = connectionObjectRdbService.findByFbAccountId(fbAccountId, 2);
				if (CollectionUtils.isEmpty(connectionObjects)) {
					logger.warn(fbAccountId + "账号下没有应用!");
					continue;
				}
				for (ConnectionObject connectionObject : connectionObjects) {
				    logger.info("开始获取账号{}下应用{}的cpa权限信息",fbAccountId,connectionObject.getName());
					fbAdDestination = this.getFBAdDestination(connectionObject.getFbConnectionObjectId(), fbAccountId, token);
					if(fbAdDestination==null||fbAdDestination.getMobileAppCpaAccess()==null){
						logger.warn(fbAccountId + "账号下"+connectionObject.getName()+"没有CPA权限描述信息!");
						continue;
					}
					Boolean ios = fbAdDestination.getMobileAppCpaAccess().getItunes()==null?false:fbAdDestination.getMobileAppCpaAccess().getItunes();
					Boolean google = fbAdDestination.getMobileAppCpaAccess().getGooglePlay()==null?false:fbAdDestination.getMobileAppCpaAccess().getGooglePlay();
					Boolean fbCavas = fbAdDestination.getMobileAppCpaAccess().getFbCanvas()==null?false:fbAdDestination.getMobileAppCpaAccess().getFbCanvas();
					List<ProductConfiguration> productConfigurations = productConfigurationRdbService.findByFbConnectionObjectId(connectionObject.getFbConnectionObjectId());
					for(ProductConfiguration productConfiguration:productConfigurations){
						AdPublishAppAccountCPA adPublishAppAccountCPA = new AdPublishAppAccountCPA();
						adPublishAppAccountCPA.setProductConfigurationId(productConfiguration.getId());
			            adPublishAppAccountCPA.setConnectionObjectId(productConfiguration.getFbConnectionObjectId());
			            adPublishAppAccountCPA.setFbAccountId(fbAccountId);
						if(productConfiguration.getPlatform().equals("itunes")){
							adPublishAppAccountCPA.setSupportCPA(ios);
							logger.info("开始获取账号{}下应用{}的{}平台cpa权限为{}",fbAccountId,connectionObject.getName(),productConfiguration.getPlatform(),ios);
						}
						if(productConfiguration.getPlatform().equals("google_play")){
							adPublishAppAccountCPA.setSupportCPA(google);
							logger.info("开始获取账号{}下应用{}的{}平台cpa权限为{}",fbAccountId,connectionObject.getName(),productConfiguration.getPlatform(),google);
						}
						
						adPublishAppAccountCPARdbService.saveOrUpdateCPANoUser(adPublishAppAccountCPA);
					}
				}

			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	private FBAdDestination getFBAdDestination(Long fbConnectionObjectId, Long fbAccountId,
			String accessToken) {
		FBAdDestination fbAdDestination = null;
		// TODO Auto-generated method stub
		SearchParam searchParam = new SearchParam();
		searchParam.setObjectId(fbConnectionObjectId);
		searchParam.setType(SearchType.ADDESTINATION.getType());
		searchParam.setFbAccountId(fbAccountId);
		searchParam.setAccessToken(accessToken);
		try {
			List<FBAdDestination> list = serchFBService.search(searchParam,
					FBAdDestination.class);
			if (!CollectionUtils.isEmpty(list)) {
				fbAdDestination = list.get(0);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return fbAdDestination;
	}
}
